<?php

namespace App\Http\Controllers\Api\V6;

use App\Http\Controllers\Controller;
use App\Models\V6\CompanyModel;
use App\Models\V6\MemberModel;
use App\Models\V6\ReadPartyModel;

use App\Repository\Comment;
use Dingo\Api\Routing\Helpers;
use Illuminate\Http\Request;
use App\Common\ApiData;
use Illuminate\Support\Facades\DB;

class AddressListController extends Controller
{
    use Helpers, Comment;

    //读书会通讯录---获取所有的工作人员【添加个人地区 公司部门】
    public function getAllMember(Request $request)
    {
        $apiData     = new ApiData();
        $readPartyId = $request->input('readPartyId');
        $page        = $request->input('page');
        $keyword     = $request->input('keyword');
        $mobile      = $request->input('mobile');
        $key         = $request->input('key');
        $depatmentId = $request->input('departmentId', -1);
        $depatmentId = $depatmentId === '' ? -1 : $depatmentId;

        $params = [
            'mobile' => [$mobile, "缺少手机号", 2037],
            'key'    => [$key, "缺少设备ID", 2038],
            'id'     => [$readPartyId, "缺少读书会ID", 2039]
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false)
        {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false)
        {
            $apiData->message = "用户不存在";
            $apiData->code    = 3027;
            return $apiData->send();
        }


        //读书会信息
        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        if (!$readPartyInfo)
        {
            $apiData->message = "读书会不存在";
            $apiData->code    = 402;
            return $apiData->send();
        }


        //如果是企业读书会 并且传递的是department_id是存在的
        if ($readPartyInfo->ReaParType == 1 && $depatmentId >= 0)
        {
            $data = $this->getDepartmentUser($request);
            return $this->response->array(['code' => 200, 'message' => '获取部门列表成功', 'data' => $data]);
        }

        $readPartyMembers = $readPartyModel->get_read_party_member($readPartyId, $keyword, 1000);

        //1.根据read_party表的ReadParType的类型判断是否是企业还是个人1为企业2为个人
        $readType = DB::table('read_party')->where('ReaParID', $readPartyId)
            ->pluck('ReaParType')->toArray();
        //根据类型---1.企业人员情况显示部门，与人员的身份 2.个人情况显示的是地区与是否是管理员
        $company_id = $this->getCompanyIdByReadPartId($readPartyId);
        if ($readType[0] == 1) {//企业类型
            foreach ($readPartyMembers as $k => $v)
            {
                $role = $this->isDrp($v->UserID, $company_id);
                if ($role) {
                    $v->isAdmin = 2;//学习官
                } elseif ($v->MemNumber == $readPartyInfo->MemNumber) {
                    $v->isAdmin = 1;//管理员
                } else {
                    $v->isAdmin = 0;//普通人
                }
                //(2)判断用户所属的部门根据company_user的department_id的id找到company_department的id找到department_name
                /*
                 $departmentInfo  = DB::table('company_department as cd')
                    ->select('cd.department_name', 'cd.department_id', 'cu.job', 'cd.company_id')
                    ->leftJoin('company_user as cu', 'cd.department_id', '=', 'cu.department_id')
                    ->where(['cu.user_id' => $v->UserID, 'cu.company_id' => $company_id, 'cu.is_delete' => 0])
                    ->get();
                */

                $city              = $this->get_city_by_user_id($v->UserID);
                $v->city           = $city;
                //$v->departmentInfo = $departmentInfo;

                $v->departmentInfo = [[
                    "department_name"=> $v->department_name,
                    "department_id"=> 0,
                    "job"=> "观察员",
                    "company_id"=> 0]];
            }
        } else {//个人类型
            //(1)判断用户的地址信息
            foreach ($readPartyMembers as $k => $v) {
                if ($v->MemNumber == $readPartyInfo->MemNumber) {
                    $v->isAdmin = 1;//1是管理员
                } else {
                    $v->isAdmin = 0;//0不是管理员
                }
                $city    = $this->get_city_by_user_id($v->UserID);
                $v->city = $city;
            }
        }
        return $this->response->array(['code' => 200, 'message' => '获取通讯录成功', 'data' => $readPartyMembers]);
    }

    //部门通讯录添加部门的管理人员
    public function addDepartmentAdmin($readPartyId, $userMemNumber, $mobile, $key, $departmentId, $userId)
    {
//        $readPartyId   = $readPartyId;
//        $userMemNumber = $userMemNumber;//当前执行操作的用户的memNumber
//        $mobile        = $mobile;
//        $key           = $key;
//        $departmentId  = $departmentId;
//        $userId        = $userId;//被设置为部门管理员的user_id
        $readPartyModel = new ReadPartyModel();
        //1.判断用户的身份
        $isAdmin = $this->hasAdmin($readPartyId, $userMemNumber);//管理员
        $isDrp   = $this->hasDrp($mobile, $key, $readPartyId);//学习官
        //判断要成为主管的人是否是学习官或者是管理员
        $companyId = $this->getCompanyIdByReadPartId($readPartyId);
        $youAreDrp = $this->isDrp($userId, $companyId);
        if ($youAreDrp) {
            return $this->response->array(['code' => 400, 'message' => '你不能设置学习官为主管', 'data' => []]);
        }

        if ($isDrp || $isAdmin) {//管理员或者学习官有这个权限
            //1.判断这个部门是否已经存在主管了
            //$user = $this->hasDepartmentAdmin($departmentId);
            //如果主管已经存在了，则取消管理员的身份
            $status = $readPartyModel->addCompanyDepartmentAdmin($departmentId, $userId);//更新部门的管理员
            return $status;
        }
        return $status = 0;
    }

    //获取读书会的部门成员 1.个人读书会显示管理员 2.公司读书会显示主管 ----组织结构模块
    public function getDepartmentUser(Request $request)
    {
        $mobile       = $request->input('mobile');
        $key          = $request->input('key');
        $readPartyId  = $request->input('readPartyId'); //读书会的ID
        $departmentId = $request->input('departmentId'); //部门的ID


        $is_admin_user = DB::table('company_department')
            ->where('department_id', $departmentId)
            ->first(['department_manager']);

        $is_admin_user = $is_admin_user ? $is_admin_user->department_manager : '';

        $readPartyModel = new ReadPartyModel();
        $members        = $readPartyModel->get_read_party_department_member($readPartyId, $departmentId);
        $readpartyInfo  = $readPartyModel->get_read_party_info($readPartyId);

        if ($readpartyInfo->ReaParType == 1) {//企业
            foreach ($members as $key => $value) {
                $city           = $this->get_city_by_user_id($value->UserID);
                $value->city    = $city;
                $value->isAdmin = ($value->UserID == $is_admin_user) ? 3 : 0;//3是主管 0不是主管
                $value->job     = "";
            }
        } else {//个人
            foreach ($members as $key => $value) {
                $status         = $this->hasAdmin($readPartyId, $value->MemNumber);
                $value->isAdmin = $status;//1是管理员 0不是管理员
                $value->job     = "";
            }
        }
        return $members;
    }

    //会员信息的修改
    public function update_read_party_member(Request $request)
    {
        $mobile       = $request->input('mobile');
        $key          = $request->input('key');
        $departmentId = $request->input('departmentId');
        $readPartyId  = $request->input('readPartyId');
        $job          = $request->input('job');
        $rewardRight = $request->input('rewardRight');
        $userId      = $request->input('userId');//被修改的人的user_id
        $userMobile  = $request->input('userMobile');//被修改的人的phone


        //$memnumber   = $request->MemNumber;//当前执行操作的用户的memnumber
        //$type         = $request->type;//是否设置为部门的主管1为设置为部门的主管，0表示不设置为部门的主管


        $apiData = new ApiData();

        $params = [
            //'departmentId' => [$departmentId, '缺少部门ID', 2003],
            'job'        => [$job, '缺少工作名称', 2004],
            'userMobile' => [$userMobile, '修改的手机号为空', 2006],
            'userId'     => [$userId, '用户的ID为空', 2007]
        ];
        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
            return $apiData->send();
        }

        if(!preg_match('/^\d{5,20}$/',$userMobile))
        {
            return $apiData->send(2000,"手机号格式错误");
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = 2001;
            return $apiData->send();
        }



        //学习官或者管理员设置部门主管
//        if ($type == 1) {//如果type为1表示要设置部门的管理员
//            //1.根据departmentId判断要设置为部门主管的人是否已经存在在这个部门里面了
//            $departmentInfo = DB::table('company_user')->where('department_id', $departmentId)->get(['user_id'])->toArray();
//            $tmp            = [];
//
//            foreach ($departmentInfo as $k => $v) {
//                array_push($tmp, $v->user_id);
//            }
//            if (!in_array($userId, $tmp)) {//如果用户不存在这个部门
//                return $this->response->array(['code' => 404, 'message' => '用户不存在这个部门', 'data' => []]);
//            }
//            //2.如果用户存在在这个部门里面了
//            $status = $this->addDepartmentAdmin($readPartyId, $memnumber, $mobile, $key, $departmentId, $userId);//
//            if ($status == 0) {
//                return $this->response->array(['code' => 403, 'message' => '抱歉设置管理员失败了', 'data' => []]);
//            }
//        }

        $updatedUserInfo = $memberModel->get_member_info_by_id($userId);
        if ($updatedUserInfo == false) {
            $apiData->message = "被修改的用户不存在";
            $apiData->code    = 2002;
            return $apiData->send();
        }

        //检查新的手机号是否和旧的手机号相同 不同  则为修改  那么检查新的手机号是否已被占用
        if($updatedUserInfo->UserName != $userMobile)
        {
            $hasUser    = $memberModel->get_member_info_by_mobile($userMobile);
            if($hasUser)
            {
                return $apiData->send(2004,$userMobile."已被使用");
            }
        }

        $readPartyModel = new ReadPartyModel();
        $readPartyInfo  = $readPartyModel->get_read_party_info($readPartyId);
        $companyId      = $readPartyInfo->company_id;

        $companyModel = new CompanyModel();

        

        //修改用户公司信息, 'department_id' => $departmentId 去除部门修改的
        $companyMemberInfo = ['job' => $job, 'department_id' => $departmentId];
        $companyModel->update_company_member($userId, $companyId, $companyMemberInfo);

        //修改用户基本信息
        $modifyInfo = [
            'UserID'   => $updatedUserInfo->UserID,
            'UserName' => $userMobile
        ];

        $memberModel->update_member_info($modifyInfo);


        //修改读书会相关信息
        //$partyMemberInfo = ['reward_right' => $rewardRight];
        $partyMemberInfo = ['reward_right' => $rewardRight,'department_id'=>$departmentId];
        $readPartyModel->update_read_party_member($readPartyId, $userId, $partyMemberInfo);
        return $apiData->send(200, "修改成功");

    }

}